package com.sckj.view;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

import com.sckj.config.SysConfig;
import com.sckj.config.ViewCfg;
import com.sckj.dto.ResultVo;
import com.sckj.thread.IpPortThread;
import com.sckj.util.CommonUtil;
import com.sckj.util.DocColorUtil;
import com.sckj.util.PublicConstant;

public class MainView extends JFrame {
	private static final long serialVersionUID = 1L;
	public static final int width = 400;
	public static final int height = 800;

	private Thread thread; // 标题栏时间进程
	private Thread mainThread; // 主内容进程
	JPanel showTxt=new JPanel();
//	JTextArea msg_textArea=new JTextArea(6, 35);
	JTextPane textPane=new JTextPane();
	JScrollPane jScrollPane = new JScrollPane(textPane);
	private String message="";//消息
	private boolean rst=true;	//主线程控制
	
	public MainView(){
		// 窗体大小以及起始位置等基本参数设定
		super("服务器监听：" + CommonUtil.dateToString(new Date(), PublicConstant.DATE_FORMAT_STRING_DEFAULT));
		setSize(width, height);
		setResizable(false);
		setLocation(600, 200);
		setLayout(null);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		add(showTxt);		
		
		showTxt.setBounds(0, 0, ViewCfg.WIDTH, ViewCfg.HEIGHT);
		showTxt.setLayout(null);
		showTxt.setBackground(Color.WHITE);		

		jScrollPane.setBounds(10, 10, 380, 750);
		//,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
//		jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

//		msg_textArea.setLineWrap(true);        //激活自动换行功能 
//		msg_textArea.setWrapStyleWord(true);            // 激活断行不断字功能
//		msg_textArea.setEditable(false); 
//		msg_textArea.setFont(new Font("宋体", Font.PLAIN,18));
	
		showTxt.add(jScrollPane);
		add(showTxt);
		// 定义方法获取时间
		// 开启进程更新标题栏时间
		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					// 将标签的横坐标用变量表示
					try {
						thread.sleep(1000); // 使线程休眠1000毫秒
						MainView.this.setTitle("服务器监听：" + CommonUtil.dateToString(new Date(), PublicConstant.DATE_FORMAT_STRING_DEFAULT));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
		thread.start();

		mainThread =new Thread(new Runnable() {			
			@Override
			public void run() {
				while (rst) {
					String ipProts=SysConfig.LISTEN_IP_PORT_LIST;
					if(ipProts==null || ipProts.isEmpty()){
						rst=false;
						refreshTextArea("没有监听的Ip",Color.RED);
						break;
					}
					String[] ips=SysConfig.LISTEN_IP_PORT_LIST.split(",");
					if(ips==null || ips.length<=0){
						rst=false;
						refreshTextArea("没有监听的Ip",Color.RED);
						break;
					}else {
						String ipReg="\\p{Alnum}*\\.\\p{Alnum}*\\.\\p{Alnum}*\\.\\p{Alnum}*";
						String ipPortReg="\\p{Alnum}*\\.\\p{Alnum}*\\.\\p{Alnum}*\\.\\p{Alnum}* ([0-9]|[1-9]\\d{1,3}|[1-5]\\d{4}|6[0-5]{2}[0-3][0-5])";
						ResultVo<Object> result=new ResultVo<>();						
						for (int i=0;i<ips.length;i++) {							
							String ip=ips[i];
							DocColorUtil.insertDocument(textPane,"连接"+ip+":",Color.BLACK);
							if (!ip.isEmpty() && ip.matches(ipReg)) {	//ip验证
								result=runByIp(ip);	
							} else if(!ip.isEmpty() && ip.matches(ipPortReg)){	//ip加端口验证
								result=runByIpAndPort(ip);
							}else{	//错误的ip格式
								result.setRst(false);
								result.setMessage("错误的ip格式");
								//JOptionPane.showMessageDialog(null, "Pleage input the correct message");
							}		
							//设置背景色
							if(result.isRst()){
								refreshTextArea(result.getMessage()+"\n",Color.GREEN);
							}else{
								refreshTextArea(result.getMessage()+"\n",Color.RED);
							}
													
						}	
						refreshTextArea("----------------------------\n",Color.BLACK); 					
						try {
							IpPortThread.sleep(SysConfig.LISTEN_SLEEP_TIME);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
		mainThread.start();
	}
	//跳转到滚动条最底部
	JScrollBar scrollBar=jScrollPane.getVerticalScrollBar();
	//每次需要在JTextArea增加String时,调用如下方法
	private void refreshTextArea(String text,Color color){
			DocColorUtil.insertDocument(textPane,text,color);

	        //在更新logArea后，稍稍延时，否则getMaximum（）获得的数据可能不是最后的最大值，无法滚动到最后一行
	        try {
	            Thread.sleep(100);
	        } catch (InterruptedException ex) {
//	            Logger.getLogger(TestServer.class.getName()).log(Level.SEVERE, null, ex);
	        }
	        scrollBar.setValue(scrollBar.getMaximum());
	    }
	
	public static void main(String[] args) {
		new MainView();
	}
	
	/**
	 * 运行ip
	 */
	public ResultVo<Object> runByIp(String ip) {
		System.out.println("开始验证ip");
		ResultVo<Object> result=new ResultVo<>();
		boolean rst=false;
		message="失败！";
		try {
			// 获得所ping的IP进程，-w 280是等待每次回复的超时时间，-n 1是要发送的回显请求数
			Process process = Runtime.getRuntime().exec("ping " + ip + " -w 280 -n 1");
			InputStream is = process.getInputStream();// 获得进程的输入流对象
			InputStreamReader isr = new InputStreamReader(is, Charset.forName("GBK"));// 创建InputStreamReader对象
			BufferedReader in = new BufferedReader(isr);// 创建缓冲字符流对象
			String line = in.readLine();// 读取信息
			while (line != null) {
				if (line != null && !line.equals("")) {
					System.out.println("line=="+line);
					if (line.substring(0, 2).equals("来自")
							|| (line.length() > 10 && line.substring(0, 10).equals("Reply from"))) {// 判断是ping通过的IP地址
						rst = true;
						message="成功！";
						System.out.println("-----------------------------");
					}
				}
				line = in.readLine();// 再读取信息
			}			
			in.close();
			isr.close();
			is.close();			
		} catch (IOException e) {
			message="异常！";
		}
		System.out.println("结束验证ip");
		result.setRst(rst);
		result.setMessage(message);
		return result;
	}
	/**
	 * 运行ip和端口监听
	 */
	public ResultVo<Object> runByIpAndPort(String ip) {
		System.out.println("开始验证ip端口");
		ResultVo<Object> result=new ResultVo<>();
		boolean rst=false;
		message="失败！";
		try {
			// 获得所ping的IP进程，-w 280是等待每次回复的超时时间，-n 1是要发送的回显请求数
			Process process = Runtime.getRuntime().exec("tcping " + ip);
			InputStream is = process.getInputStream();// 获得进程的输入流对象
			InputStreamReader isr = new InputStreamReader(is, Charset.forName("GBK"));// 创建InputStreamReader对象
			BufferedReader in = new BufferedReader(isr);// 创建缓冲字符流对象
			String line = in.readLine();// 读取信息
			while (line != null) {
				System.out.println("line=="+line);
				if (line != null && !line.equals("")) {
					if (line.contains("Port is open")) {// 判断是ping通过的IP地址
						System.out.println("ip端口已ping通");
						rst = true;
						message="成功！";
					}
				}
				line = in.readLine();// 再读取信息
			}
			in.close();
			isr.close();
			is.close();
		} catch (IOException e) {
			message="异常！";
		}
		System.out.println("结束验证ip端口");
		result.setRst(rst);
		result.setMessage(message);
		return result;
	}
	
}
